package com.jt.service;


import com.jt.mapper.FileMapper;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    private String localDirPath = "E:/cgb2108/images";
    @Override
    public ImageVO upload(MultipartFile file) {
        String filename = file.getOriginalFilename().toLowerCase();
        if (!filename.matches("^.+\\.(jpg|png|gif)$"))
            return null;
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage.getHeight() == 0 || bufferedImage.getWidth() == 0)
                return null;
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String dateDirPath = localDirPath + dateDir;
            File dirFile = new File(dateDirPath);
            if (!dirFile.exists())
                dirFile.mkdirs();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newFileName = uuid + filename.substring(filename.lastIndexOf("."));
            String path = dateDirPath + newFileName;
            String url = "https://img14.360buyimg.com/n1/s546x546_jfs/t1/222493/36/2768/130956/61921070Ee4e511a5/762496ebd05718f9.jpg";
            return new ImageVO(path,url,newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
